package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 处理支付超时订单，每分钟处理一次
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void processTimeoutOrder(){
        log.info("处理支付超时订单：{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        // 查询所有未支付的超时订单
        List<Orders> ordersList = ordersMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);

        // 将未支付的超时订单的状态设置为已取消
        if (ordersList != null && !ordersList.isEmpty()){
            ordersMapper.batchCancelOrdersByIds(ordersList.stream().map(Orders::getId).collect(Collectors.toList()), Orders.CANCELLED, LocalDateTime.now(), "订单超时自动取消");
        }
    }

    /**
     * 处理“派送中”状态的订单，每天的凌晨一点处理一次
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中订单：{}", LocalDateTime.now());

        // 查询前一天所有派送中的订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = ordersMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);

        // 将前一天所有派送中的订单状态设置为已完成
        if (ordersList != null && !ordersList.isEmpty()){
            ordersMapper.batchSetStatusCompletedByIds(ordersList.stream().map(Orders::getId).collect(Collectors.toList()), Orders.COMPLETED);
        }
    }

}
